#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：zip_folder 
@File ：zip_folder.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/7/30 下午7:48 
"""

import os
import re
import subprocess


def get_folder_names(path):
	return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]


def filter_and_sort_folders(path, special_str, folder_names):
	digit_only_folders = [f for f in folder_names if re.match("^\d+$", f) and special_str in f]
	# 反转排序结果，使更早修改的文件夹排在前面
	sorted_folders = sorted(digit_only_folders, key=lambda x: os.path.getmtime(os.path.join(path, x)), reverse=False)
	return sorted_folders


def find_matching_folder(sorted_folders, index):
	# 根据索引选择文件夹，索引从0开始
	if index < len(sorted_folders):
		return sorted_folders[index]
	return None


def find_target_folder(sorted_folders, date_str, seq_num):
	# 遍历排序后的文件夹列表，寻找匹配日期的文件夹
	for folder in sorted_folders:
		if date_str in folder:
			seq_num -= 1
			if seq_num == 0:
				return folder
	return None


def compress_folders(folder1, folder2, output_name):
	cmd = f'"D:\\Program Files\\7-Zip\\7z.exe" a -tzip "{output_name}.zip" "{folder1}/*" "{folder2}/*"'
	subprocess.run(cmd, shell=True)


def process_input(input_str, path):
	# 拆分输入的字符串
	inputs = [s.strip() for s in re.split(r'[,;]\s*', input_str)]
	for date_str in inputs:
		# 假设每个输入的字符串格式为"日期序号"
		seq_num = int(date_str[-2:])
		date_str = date_str[:-2]

		sorted_folders = filter_and_sort_folders(path, date_str, get_folder_names(path))
		target_folder = find_matching_folder(sorted_folders, seq_num - 1)  # 序号减1因为索引从0开始

		if target_folder:
			print(f"找到目标文件夹：{target_folder}")

			# 再次搜索匹配的文件夹
			folder_names = get_folder_names(path)
			second_folder = next((f for f in folder_names if target_folder in f and f != target_folder), None)
			if second_folder:
				print(f"找到第二个匹配的文件夹：{second_folder}")

				# 压缩文件名，选择包含非数字的文件夹名
				non_digit_folders = [f for f in folder_names if not f.isdigit() and second_folder in f]
				if non_digit_folders:
					output_name = non_digit_folders[0].replace("/", "_") + "_" + date_str + "_" + str(
						seq_num)  # 替换路径分隔符为下划线
					compress_folders(target_folder, second_folder, output_name)
					print(f"压缩文件已创建：{output_name}.zip")
				else:
					print("未找到包含非数字的文件夹名。")
			else:
				print("未找到第二个匹配的文件夹。")
		else:
			print(f"未找到序号为{seq_num}的文件夹。")


def main():
	path = os.getcwd()
	input_str = input("请输入字符串，使用逗号或分号隔开：")
	process_input(input_str, path)


if __name__ == '__main__':
	main()
	input("Press Enter to exit...")
